// 加载所需模块
const db = require('../db');
const utils = require('utility');
const jwt = require('jsonwebtoken');
// 1.加载express
const express = require('express');
// 2.创建路由对象（一般叫他对象，实际上他是函数）
const router = express.Router();
// 3.把接口挂载到router上
// ----------------------------- 注册接口 --------------------------
router.use(express.urlencoded({ extended:false }));
router.post('/reguser',(req,res) => {
    // 作为接口，接受账号和密码，然后添加入库，最后做出响应
    db('select * from user where username=?',req.body.username,(e,r) =>{
        if(e) throw e;
        if(r.length ===0){
            req.body.password = utils.md5(req.body.password);
            db('insert into user set ?',req.body,(err,result) =>{ 
                if(err) throw err;
                if(result.affectedRows > 0){
                    res.send({
                        status:0,
                        message:'注册成功'
                    });
                }else{
                    res.send({
                        status:1,
                        message:'注册失败'
                    });
                }
            })
        }else {
            res.send({status:1,message:'用户名被占用'});
        }
    });
    

})
// ----------------------------- 登录接口 --------------------------
router.post('/login',(req,res) => {
    // 获取账号密码
    let username = req.body.username;
    let password =utils.md5(req.body.password); //把密码加密，然后才能和数据库保存的密码进行对比
    db('select * from user where username=? and password=?',[username,password],(err,result) =>{
        if(err) throw err;
        if(result.length === 0) {
            res.send({
                status:1,
                message:'账号或密码错误'
            });
        }else{
            res.send({
                status:0,
                message:'登录成功',
                token: 'Bearer ' + jwt.sign({ id:result[0].id },'bigeventserver107',{ expiresIn: '2 days' })
            });
        }
    });
})
// 4.暴露 router
module.exports = router;